package com.app.controller;

import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import com.app.utils.DB;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.app.entity.*;
import com.app.service.*;
import com.app.utils.MD5;
import com.app.utils.MainUtils;

@Controller
@RequestMapping("/index")
public class IndexController {

	@Resource
	UsersService userService;
	@Resource
	GoodsService gService;
	@Resource
	InfocateService cService;
	@Resource
	NewsService nService;
	@ResponseBody
	@RequestMapping("/getThread")
	public long getThread(HttpSession sess) throws Exception {
		long resp=0;
		if(sess.getAttribute("inDate")==null){
			sess.setAttribute("inDate", System.currentTimeMillis());
		}else{
			String inDate =  sess.getAttribute("inDate").toString();
			//String nowDate = MainUtils.getTime();
			//MainUtils.compareDdate(DATE1, DATE2)
			//时间处理类
            //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long currentTime =System.currentTimeMillis();
            //从对象中拿到时间
            long createTime = Long.parseLong(inDate);
            long diff=(currentTime-createTime)/1000;
            resp=diff;
            System.out.println("当前系统时间为："+currentTime+"进入时间为："+createTime+"两个时间差为："+diff);
		}
		return resp;
	}
	@RequestMapping("/report")
	public String buy(Model model) {

		model.addAttribute("n1", userService.getUsersByType(1).size());
		model.addAttribute("n2", userService.getUsersByType(2).size());
		model.addAttribute("n3", ordertabService.getAllOrdertab().size());
		model.addAttribute("n4", nService.getAllNews().size());
		model.addAttribute("n5", questionService.getAllQuestion().size());
		// model.addAttribute("n6", .size());

		return "admin/report";
	}

	@RequestMapping("/chat")
	public String chat(String type, Model model) {
		model.addAttribute("clist", cService.getAllInfocate());
		model.addAttribute("question_category", "1");

		List<Question> list = questionService.getAllQuestion();
		for (Question question : list) {
			question.setUser(userService.getUsersById(
					Integer.parseInt(question.getUserid())).getUsername());
		}

		model.addAttribute("list", list);
		model.addAttribute("list2", questionService.getRandQuestion());
		return "index/chat";
	}

	@RequestMapping("/tech")
	public ModelAndView tech() {
		ModelAndView mav = new ModelAndView("index/tech");

		mav.addObject("clist", cService.getAllInfocate());
		List<Cates> cates = caService.getByPid("0");
		mav.addObject("cates", getChild(cates));

		mav.addObject("ls", userService.getUsersByType(2));
		return mav;
	}

	@RequestMapping("/news")
	public String news(String cateId, String key, Model model) {

		List<News> blTj = nService.getNewsRand2();
		List<News> nList = nService.getAllNews();
		Infocate cate = null;
		if (cateId != null) {
			nList = nService.getNewsByCateId(Integer.parseInt(cateId));
			// blTj = nService.getNewsRand(Integer.parseInt(cateId));
			cate = cService.getInfocateById(Integer.parseInt(cateId));
		}
		if (key != null) {
			key = MainUtils.encode(key);
			key = "%" + key + "%";
			nList = nService.getNewsLike(key);
		}

		for (News news : nList) {
			news.setCate(cService.getInfocateById(Integer.parseInt(news
					.getUid())));
		}

		model.addAttribute("cate1", cate);
		model.addAttribute("cList", nList);
		model.addAttribute("blTj", blTj);
		model.addAttribute("clist", cService.getAllInfocate());
		List<Cates> cates = caService.getByPid("0");
		model.addAttribute("cates", getChild(cates));
		return "index/news";
	}

	public boolean checkApplyed(String uid) {
		boolean isApplyed = false;
		List<Ordertab> ordertabList = ordertabService.getAllOrdertab();
		List<Ordertab> ordertabList1 = new LinkedList<Ordertab>();
		for (Ordertab ordertab : ordertabList) {
			if (uid.equals(ordertab.getUid())) {
				isApplyed = true;
			}
		}
		return isApplyed;
	}

	@RequestMapping(value = "/del")
	public ModelAndView del(int id, HttpSession session) {
		ModelAndView mav = new ModelAndView("index/chat");
		mav.addObject("type",questionService.getQuestionById(id).getQuestion_category());
		gService.delete(id);
		mav.addObject("message","删除成功");

		return mav;
		}

	@RequestMapping(value = "/yy2")
	public ModelAndView yy2(int id, HttpSession session) {
		ModelAndView mav = new ModelAndView("index/goods");

		if (session.getAttribute("user") != null) {

				Goods gs = gService.getGoodsById(id);
				Users user = userService.getUsersById(Integer.parseInt(session
						.getAttribute("userid") + ""));
				float price = 6300f;
				// float left = Float.parseFloat(user.getMoney()) - price;

				Ordertab modelS = new Ordertab();
				modelS.setOrder_id(MainUtils.getOrderIdByUUId());
				modelS.setBuyer(user.getUsername());
				modelS.setCreated(MainUtils.getTime());
				modelS.setPid(id + "");
				modelS.setUid(user.getId() + "");
				modelS.setPname(gs.getProduct_name());
				modelS.setPrice("100");
				modelS.setNum("1");
				modelS.setStep("1");

				ordertabService.insert(modelS);

				mav.addObject("inpost", "1");
				mav.addObject("message", "成功提交报名");



		} else {
			mav.addObject("inpost", "1");
			mav.addObject("message", "请您登录");
		}

		mav.addObject("clist", cService.getAllInfocate());
		List<Cates> cates = caService.getByPid("0");
		mav.addObject("cates", getChild(cates));

		mav.addObject("ls", userService.getUsersByType(2));
		return mav;
	}

	@Resource
	OrdertabService ordertabService;

	@RequestMapping("/videos")
	public String videos(String cateId, String key, Model model) {

		List<News> blTj = nService.getNewsRand2();
		List<News> nList = nService.getAllNews();
		Infocate cate = null;
		if (cateId != null) {
			nList = nService.getNewsByCateId(Integer.parseInt(cateId));
			// blTj = nService.getNewsRand(Integer.parseInt(cateId));
			cate = cService.getInfocateById(Integer.parseInt(cateId));
		}
		if (key != null) {
			key = MainUtils.encode(key);
			key = "%" + key + "%";
			nList = nService.getNewsLike(key);
		}

		for (News news : nList) {
			news.setCate(cService.getInfocateById(Integer.parseInt(news
					.getUid())));
		}

		model.addAttribute("cate1", cate);
		model.addAttribute("cList", nList);
		model.addAttribute("blTj", blTj);
		model.addAttribute("clist", cService.getAllInfocate());
		return "index/videos";
	}

	@Resource
	CommentService commentService;

	@Resource
	QuestionService questionService;

	@RequestMapping(value = "/addpost", method = RequestMethod.POST)
	public String addpost(String thumb, String short_title,
			String question_name, String question_category, String score,
			String step, String created, String status, String userid,
			String clicked, HttpSession session, Model model) {
		Question modelX = new Question();
		modelX.setShort_title(short_title);
		modelX.setQuestion_name(question_name);
		modelX.setQuestion_category(question_category);
		modelX.setScore(score);
		modelX.setStep(step);
		modelX.setThumb(thumb);
		modelX.setCreated(MainUtils.getTime());
		modelX.setUserid(session.getAttribute("userid").toString());
		modelX.setClicked("0");

		questionService.insert(modelX);
		model.addAttribute("inpost", true);
		model.addAttribute("message", "Success!");
		return "redirect:chat?type=" + question_category;
	}

	@RequestMapping(value = "/addcomment", method = RequestMethod.POST)
	public String addcomment(String uid, String mid, String content,
			String type, String created, String updated, String status,
			String subject, String pid, String username, HttpSession session,
			Model model) {
		Comment modelX = new Comment();
		modelX.setUid(session.getAttribute("userid").toString());
		modelX.setMid(mid);
		modelX.setContent(content);
		modelX.setType("1");
		modelX.setCreated(MainUtils.getTime());
		modelX.setStatus("1");
		modelX.setPid(mid);
		modelX.setUsername(session.getAttribute("username").toString());

		commentService.insert(modelX);
		model.addAttribute("inpost", true);
		model.addAttribute("message", "Success!");
		return "redirect:good?id=" + mid;
	}

	@RequestMapping("/goods")
	public String shop(Model model) {

		List<Goods> list = gService.getAllGoods();
		List<Goods> list1 = new LinkedList<Goods>();
		if (list.size() > 0) {
			for (Goods g : list) {
				g.setU(userService.getUsersById(Integer.parseInt(g.getUid())));
				list1.add(g);
			}
		}
		model.addAttribute("list", list1);
		model.addAttribute("rand", gService.getRandGoods());
		model.addAttribute("clist", cService.getAllInfocate());
		return "index/goods";
	}

	@RequestMapping("/view")
	public ModelAndView view(int id, Model model) {
		ModelAndView mav = new ModelAndView("index/view");
		News article = nService.getNewsById(id);
		article.setClick((Integer.parseInt(article.getClick()) + 1) + "");
		nService.update(article);

		model.addAttribute("art", article);
		model.addAttribute("cate1",
				cService.getInfocateById(Integer.parseInt(article.getUid())));
		model.addAttribute("ydPh", nService.getNewsRand2());
		model.addAttribute("clist", cService.getAllInfocate());

		News pre = nService.getNewsById(id - 1);
		News next = nService.getNewsById(id + 1);
		model.addAttribute("pre", pre);
		model.addAttribute("next", next);
		List<Cates> cates = caService.getByPid("0");
		model.addAttribute("cates", getChild(cates));
		return mav;
	}

	@Resource
	AnswerService answerService;

	@RequestMapping("/question")
	public ModelAndView question(int id, Model model) {
		ModelAndView mav = new ModelAndView("index/question");
		Question q = questionService.getQuestionById(id);
		q.setUser(userService.getUsersById(Integer.parseInt(q.getUserid()))
				.getUsername());
		List<Answer> list = answerService.getByQid(id);
		for (Answer answer : list) {
			answer.setUser(userService.getUsersById(
					Integer.parseInt(answer.getUid())).getUsername());
			answer.setAut(userService.getUsersById(Integer.parseInt(answer
					.getUid())));
		}

		model.addAttribute("q", q);
		model.addAttribute("list", list);
		model.addAttribute("clist", cService.getAllInfocate());

		model.addAttribute("list2", questionService.getRandQuestion());

		return mav;
	}

	@RequestMapping("/voice")
	public ModelAndView voice(Model model, HttpSession sess) {

		ModelAndView mav = new ModelAndView("index/voice");
		model.addAttribute("clist", cService.getAllInfocate());
		model.addAttribute("list", userService.getUsersByType(2));
		return mav;
	}

	@RequestMapping("/test")
	public ModelAndView test(Model model, HttpSession sess) {

		ModelAndView mav = new ModelAndView("index/test");
		model.addAttribute("clist", cService.getAllInfocate());
		List<Goods> ls = gService.getRandTest();
		sess.setAttribute("ts", ls);
		model.addAttribute("list", ls);
		return mav;
	}

	@Resource
	CatesService catesService;

	@RequestMapping("/rest")
	public ModelAndView rest(String token, Model model, HttpSession sess,
			String userid) {

		ModelAndView mav = new ModelAndView("index/rest");
		model.addAttribute("clist", cService.getAllInfocate());
		List<Tests> list2 = testsService.getTests(userid);
		List<Tests> list = testsService.getToken(token);
		int total = Integer.parseInt(list.get(0).getTotal());
		List<Cates> ls = catesService.getRange(total);
		if (ls.size() > 0) {
			model.addAttribute("rest", ls.get(0));
		}
		for (Tests t : list2) {
			System.out.println("test:" + t.getToken());
		}
		model.addAttribute("list2", list2);
		return mav;
	}

	@Resource
	TestsService testsService;

	@RequestMapping(value = "/post", method = RequestMethod.POST)
	public String post(HttpSession sess, HttpServletRequest req, Model model) {
		String uid = sess.getAttribute("userid").toString();
		List<Goods> ls = (List) sess.getAttribute("ts");
		String token = UUID.randomUUID().toString();
		int total = 0;
		for (Goods g : ls) {
			Integer ans = Integer.parseInt(req.getParameter("answer"
					+ g.getId()));
			total += ans;
			Tests modelX = new Tests();
			modelX.setToken(token);
			modelX.setUid(uid);
			modelX.setQid(g.getId() + "");
			modelX.setScore(ans.toString());
			// modelX.setTotal(total);
			modelX.setCreated(MainUtils.getTime());
			// modelX.setRest();
			// modelX.setDescrib(describ);
			testsService.insert(modelX);
		}

		for (Tests t : testsService.getToken(token)) {
			t.setTotal(total + "");
			testsService.update(t);
		}

		model.addAttribute("message", "测试成功");
		model.addAttribute("url", "index/rest?token=" + token + "&userid="
				+ uid);

		return "index/test";
	}

	@RequestMapping(value = "/sendmsg", method = RequestMethod.POST)
	public String sendmsg(Integer userid, String msg, Integer type) {
		Users user = userService.getUsersById(userid);
		DB db = new DB();
		db.open();
		String sql = " INSERT INTO msg(userid,username,msg,type,created)";
		sql += " VALUES('" + userid + "','" + user.getUsername() + "','" + msg
				+ "','" + type + "','" + MainUtils.getTime() + "')";
		try {
			db.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@ResponseBody
	@RequestMapping("/getmsg")
	public List<Msg> getmsg() {
		DB db = new DB();
		db.open();
		ResultSet rs = null;
		try {
			rs = db.executeQuery("SELECT * from msg order by id desc");
			List<Msg> ls = new LinkedList<Msg>();
			while (rs.next()) {
				Msg msg = new Msg();
				msg.setCreated(rs.getString("created"));
				msg.setId(rs.getInt("id"));
				msg.setMsg(rs.getString("msg"));
				msg.setType(rs.getInt("type"));
				msg.setUsername(rs.getString("username"));
				msg.setUserid(rs.getInt("userid"));
				ls.add(msg);
			}
			return ls;

		} catch (SQLException e) {
			e.printStackTrace();
		}

		return null;
	}

	@RequestMapping(value = "/addans", method = RequestMethod.POST)
	public String answerSave(String support, String uid, String qid,
			String answer, String created, String status, String is_true,
			HttpSession session, Model model) {
		Answer modelX = new Answer();
		modelX.setSupport(support);
		modelX.setUid(session.getAttribute("userid").toString());
		modelX.setQid(qid);
		modelX.setAnswer(answer);
		modelX.setCreated(MainUtils.getTime());
		modelX.setStatus(status);
		modelX.setIs_true(is_true);

		answerService.insert(modelX);
		model.addAttribute("inpost", true);
		model.addAttribute("message", "Success!");
		return "redirect:question?id=" + qid;
	}

	@RequestMapping("/good")
	public ModelAndView good(int id, Model model) {
		ModelAndView mav = new ModelAndView("index/good");
		Goods good = gService.getGoodsById(id);
		model.addAttribute("g", good);
		model.addAttribute("plList", commentService.getAllCommentByMid(id));

		model.addAttribute("clist", cService.getAllInfocate());
		return mav;
	}

	@RequestMapping("/index")
	public String index(Model model,HttpSession sess) {
		//sess.setAttribute("inDate", MainUtils.getTime());
		List<News> nList = nService.getAllNews();

		model.addAttribute("clist", cService.getAllInfocate());

		List<Infocate> list = cService.getAllInfocate();
		List<Infocate> list1 = new ArrayList<Infocate>();

		for (Infocate infocate : list) {
			List<News> nL = nService.getNewsByCateId(infocate.getId());
			if (nL.size() > 0) {
				infocate.setF(nL.get(0));
			}
			infocate.setList(nL);
			if (nL.size() > 0) {
				list1.add(infocate);
			}
		}
		model.addAttribute("list", list1);

		model.addAttribute("nlist", nList);

		List<Cates> cates = caService.getByPid("0");
		model.addAttribute("cates", getChild(cates));
		model.addAttribute("newsList", nService.getNewsRand2());

		return "index/index";
	}

	@Resource
	CatesService caService;

	public List<Cates> getChild(List<Cates> list) {

		if (list.size() > 0) {
			for (Cates category : list) {

				List<Cates> subList = caService.getByPid(category.getId() + "");
				category.setSubs(getChild(subList));
			}
		}

		return list;
	}
}
